package com.mengwen.backstage.util;


import com.mengwen.backstage.config.WeChatConfig;
import com.mengwen.backstage.pojo.AccessToken;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

import static com.mengwen.backstage.util.WeixinUtil.httpRequest;

/**
 * @author LiangYonghui
 * @date 2020/4/7 11:53
 * @description 获取最新全局access_token的工具类
 */
@Component
public class GetLastAccessTokenUtil {

    @Autowired
    WeChatConfig weChatConfig;


    @Autowired
    private RedisTemplateUtil redisTemplateUtil;




    /**
     * 获取最新的acces_token
     * @return
     * @throws Exception
     */
    public AccessToken getAccessToken() throws Exception {
        String getAccessTokenUrl = weChatConfig.getWxOaGetAccessTokenUrl();
        AccessToken accessToken = null;
        String redisAccessTokenString = (String)redisTemplateUtil.get("my:accesstoken:string");
        if ("".equals(redisAccessTokenString) || redisAccessTokenString == null) {
            String requestUrl = getAccessTokenUrl.replace("APPID", weChatConfig.getAppId())
                    .replace("APPSECRET", weChatConfig.getAppsecret());
            JSONObject jsonObject = httpRequest(requestUrl, "GET", null);
            if (null == jsonObject)
            {
                throw new Exception("获取token失败");
            }

            System.out.println("从微信服务器获取凭证："+jsonObject.toString());
            accessToken = new AccessToken();
            accessToken.setToken(jsonObject.getString("access_token"));
            accessToken.setExpiresIn(jsonObject.getInt("expires_in"));
            redisTemplateUtil.set("my:accesstoken:string",jsonObject.getString("access_token"));
            redisTemplateUtil.expire("my:accesstoken:string",600);
        }else {
            System.out.println("从redis中获取凭证：");
            accessToken = new AccessToken();
            accessToken.setToken( redisAccessTokenString);
            accessToken.setExpiresIn(7200);
        }

        return accessToken;
    }



}
